﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Baidu.Aip.Nlp;
using DailyReport.Models;
using Newtonsoft.Json.Linq;

namespace DailyReport.Helpers
{
    public class DrNlpHelper
    {
        private static Nlp nlp;

        private static string apiKey = "HBFIS8yZHjp349tEY47DPdZW";
        private static string secretKey = "MUuqBAmm3nXcMLaoB1WTytUj4gf2cgEi";

        public string ApiKey
        {
            set
            {
                if (string.IsNullOrWhiteSpace(value) || value.Length < 24) return;
                apiKey = value;
                nlp = null;
            }
        }

        public string SecretKey
        {
            set
            {
                if (string.IsNullOrWhiteSpace(value) || value.Length < 32) return;
                secretKey = value;
                nlp = null;
            }
        }

        private static void StartNlp()
        {
            if (nlp == null) nlp = new Nlp(apiKey, secretKey);
        }

        #region 基础功能

        public static JObject Lexer(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return null;
            StartNlp();
            var result = nlp.Lexer(text);
            return result;
        }

        public static JObject WordEmbeddingSim(string word1, string word2)
        {
            if (string.IsNullOrWhiteSpace(word1) || string.IsNullOrWhiteSpace(word2)) return null;
            StartNlp();
            var result = nlp.WordEmbeddingSimilarity(word1, word2);
            return result;
        }

        public static JObject WordEmbeddingVector(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return null;
            StartNlp();
            var result = nlp.WordEmbeddingVector(text);
            return result;
        }

        public static JObject Dnnlm(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return null;
            StartNlp();
            var result = nlp.DNN_LM_Cn(text);
            return result;
        }

        public static JObject SimNet(string text1, string text2, BaiduAiSimnetModel model = BaiduAiSimnetModel.BOW)
        {
            if (string.IsNullOrWhiteSpace(text1) || string.IsNullOrWhiteSpace(text2)) return null;
            StartNlp();
            var options = new Dictionary<string, object>()
            {
                {"model", model.ToString()}
            };
            var result = nlp.Simnet(text1, text2, options);
            return result;
        }

        public static JObject CommentTag(string text, BaiduAiCommentType type = BaiduAiCommentType.NewTech)
        {
            if (string.IsNullOrWhiteSpace(text)) return null;
            StartNlp();

            var result = nlp.CommentTag(text, (int)type);
            return result;
        }

        public static JObject SentimentClassify(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return null;
            StartNlp();
            var result = nlp.SentimentClassify(text);
            return result;
        }

        public static JObject DepParser(string text, BaiduAiParserMode mode = BaiduAiParserMode.Web)
        {
            if (string.IsNullOrWhiteSpace(text)) return null;
            StartNlp();

            var options = new Dictionary<string, object>()
            {
                {"mode", (int)mode}
            };
            var result = nlp.DepParser(text, options);
            return result;
        }

        #endregion

        #region 用户数据分析

        public static Dictionary<string, double> GetUserSentimentQuery(string userName, DateTime startDate,
            DateTime endDate)
        {
            if (string.IsNullOrEmpty(userName) || startDate == endDate)
                return null;
            if (startDate > endDate)
            {
                DateTime dtTmp = startDate;
                startDate = endDate;
                endDate = dtTmp;
            }

            DrDbHelper dbInstance = new DrDbHelper();
            var dt = dbInstance.GetRecords(userName, startDate, endDate);
            if (dt == null || dt.Rows.Count == 0) return null;

            var dic = new Dictionary<string, double>();

            if (dt.Rows.Count <= 10)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string recDate = dr["记录时间"].ToString();
                    string remark = dr["备注"] is DBNull ? string.Empty : dr["备注"].ToString();
                    if (string.IsNullOrEmpty(remark)) continue;
                    var jObj = SentimentClassify(remark);
                    if (jObj == null || jObj.Property("items") == null || jObj["items"][0]["positive_prob"] == null)
                        continue;

                    double posProb = double.Parse(jObj["items"][0]["positive_prob"].ToString());

                    if (!dic.Keys.Contains(recDate))
                    {
                        dic.Add(recDate, posProb);
                    }
                    else
                    {
                        double newPosProb = 0.5 * (dic[recDate] + posProb);
                        dic[recDate] = newPosProb;
                    }
                }
            }
            else
            {
                //组成待求值数组
                var dtNew = dt.Copy();
                dtNew.Columns.Add("情感指数", typeof(double));
                dtNew.AcceptChanges();
                List<string> listRemark = new List<string>();
                foreach (DataRow dr in dtNew.Rows)
                {
                    string recDate = dr["记录时间"].ToString();
                    string remark = dr["备注"] is DBNull ? string.Empty : dr["备注"].ToString();
                    if (string.IsNullOrEmpty(remark)) continue;

                    listRemark.Add(remark);
                }
                //求值
                var res = DrBosonHelper.NlpSentiment(listRemark).ToArray();
                int indexRead = 0;
                foreach (DataRow dr in dtNew.Rows)
                {
                    string remark = dr["备注"] is DBNull ? string.Empty : dr["备注"].ToString();
                    if (string.IsNullOrEmpty(remark))
                    {
                        dr["情感指数"] = -1;
                    }
                    else
                    {
                        dr["情感指数"] = res[indexRead];
                        indexRead++;
                    }
                    
                }
                //更新心情值
                foreach (DataRow dr in dtNew.Rows)
                {
                    string recDate = dr["记录时间"].ToString();
                    double sentiment = Convert.ToDouble(dr["情感指数"]);
                    if (sentiment < 0) continue;

                    if (!dic.Keys.Contains(recDate))
                    {
                        dic.Add(recDate, sentiment);
                    }
                    else
                    {
                        double newPosProb = 0.5 * (dic[recDate] + sentiment);
                        dic[recDate] = newPosProb;
                    }
                }
            }

            return dic;
        }



        #endregion

    }
}